

import socket,json,ssl,common._conts
import urllib
from http import server
from http.server import SimpleHTTPRequestHandler

data = {'msg': 'val_1','code':'val_2'}
host = ('localhost', 8383)


class Resquest(SimpleHTTPRequestHandler):

    def do_GET(self):
        print(self.requestline)## TODO解析参数处理结果集
        self.send_response(200)
        self.send_header('Content-type', 'application/json')
        self.end_headers()
        str =json.dumps(data).replace('val_1','get').replace('val_2','500')
        self.wfile.write(str.encode(common._conts.CHARSET))

    # get请求
    def do_POST(self):
        length = int(self.headers['Content-Length'])
        post_data = urllib.parse.parse_qs(self.rfile.read(length).decode('utf-8'))
        print(post_data) ## TODO解析参数处理结果集
        self.send_response(200)
        self.send_header('Content-type', 'application/json')
        self.end_headers()
        str =json.dumps(data).replace('val_1','post').replace('val_2','200')
        self.wfile.write(str.encode(common._conts.CHARSET))

    # 跨域处理
    def do_OPTIONS(self):
        self.send_response(204)
        self.send_header('Content-type', 'application/json')
        self.send_header('Access-Control-Allow-Methods', 'POST,GET,OPTIONS')
        self.send_header('Access-Control-Allow-Headers', 'Content-Type, Access-Control-Allow-Headers, Authorization, X-Requested-With,Token')
        self.send_header('Access-Control-Max-Age', '1')
        self.send_header('Access-Control-Allow-Origin', '*')
        self.end_headers()
        str =json.dumps(data).replace('val_1','options').replace('val_2', '204')
        self.wfile.write(str.encode(common._conts.CHARSET))

def https_start():
    context = ssl.SSLContext(ssl.PROTOCOL_TLS_SERVER)
    context.load_cert_chain(common._conts.SSL_PEN,common._conts.SSL_KEY)#自己添加
    httpd = server.HTTPServer(host,Resquest)#  用上面的类重写
    httpd.socket = context.wrap_socket(httpd.socket, server_side=True)
    httpd.serve_forever()



def http_start():
    HOST = ''
    PORT = 8383

    index_content = '''
    HTTP/1.x 200 ok
    Content-Type: text/html
    
    '''

    #Configure socket
    sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    sock.bind((HOST, PORT))
    sock.listen(100)

    #infinite loop
    while True:
        # maximum number of requests waiting
        conn, addr = sock.accept()
        request = conn.recv(10240)
        requestStr = request.decode(encoding=common._conts.CHARSET)
        method =requestStr.split(' ')[0]

        print('Connect by: ', addr)
        print('Request is:\n', requestStr)
        form = requestStr.split('\r\n')
        entry = form[-1]
        content = 'HTTP/1.x 200 ok\r\nContent-Type: text/html\r\n\r\n'

        #deal wiht GET method
        if method == 'GET':
            content += entry
            content += "[get]"

        #deal with POST method
        elif method == 'POST':
            content += entry
            content += "[post]"

        else:
            continue

        content += '<br /><font color="green" size="7">register successs!</p>'
        conn.sendall(content.encode(encoding=common._conts.CHARSET))
        conn.close()